package com.bjbn.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.bjbn.dto.BmsApiResponse;
import com.bjbn.dto.BmsDeviceGroupDto;
import com.bjbn.dto.BmsDeviceInfoDto;
import com.bjbn.dto.BmsDeviceValueDto;
import com.bjbn.service.BmsApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BMS API服务实现类
 */
@Slf4j
@Service
public class BmsApiServiceImpl implements BmsApiService {
    
    @Value("${task.bms.base-url}")
    private String baseUrl;
    
    @Override
    public BmsApiResponse<List<BmsDeviceGroupDto>> getAllDeviceList() {
        try {
            String url = baseUrl + "/getAllDeviceList";
            log.debug("调用获取所有设备列表接口: {}", url);
            
            HttpResponse response = HttpRequest.get(url)
                    .timeout(30000)
                    .execute();
            
            if (response.isOk()) {
                String body = response.body();
                log.debug("获取所有设备列表响应: {}", body);
                
                BmsApiResponse<List<BmsDeviceGroupDto>> apiResponse = JSON.parseObject(body, 
                        new com.alibaba.fastjson2.TypeReference<BmsApiResponse<List<BmsDeviceGroupDto>>>() {});
                return apiResponse;
            } else {
                log.error("获取所有设备列表失败，状态码: {}", response.getStatus());
                return null;
            }
        } catch (Exception e) {
            log.error("获取所有设备列表异常", e);
            return null;
        }
    }
    
    @Override
    public BmsApiResponse<List<BmsDeviceInfoDto>> getDeviceTagByDeviceId(String deviceNum) {
        try {
            String url = baseUrl + "/getDeviceTagByDeviceId";
            log.debug("调用获取设备属性接口: {}, 设备编码: {}", url, deviceNum);
            
            Map<String, String> params = new HashMap<>();
            params.put("deviceNum", deviceNum);
            
            HttpResponse response = HttpRequest.post(url)
                    .body(JSONUtil.toJsonStr(params))
                    .timeout(30000)
                    .execute();
            
            if (response.isOk()) {
                String body = response.body();
                log.debug("获取设备属性响应: {}", body);
                
                BmsApiResponse<List<BmsDeviceInfoDto>> apiResponse = JSON.parseObject(body, 
                        new com.alibaba.fastjson2.TypeReference<BmsApiResponse<List<BmsDeviceInfoDto>>>() {});
                return apiResponse;
            } else {
                log.error("获取设备属性失败，状态码: {}", response.getStatus());
                return null;
            }
        } catch (Exception e) {
            log.error("获取设备属性异常", e);
            return null;
        }
    }
    
    @Override
    public BmsApiResponse<BmsDeviceValueDto> getDeviceValueByDeviceId(String deviceNum) {
        try {
            String url = baseUrl + "/getDeviceValueByDeviceId";
            log.debug("调用获取设备采集值接口: {}, 设备编码: {}", url, deviceNum);
            
            Map<String, String> params = new HashMap<>();
            params.put("deviceNum", deviceNum);
            
            HttpResponse response = HttpRequest.post(url)
                    .body(JSONUtil.toJsonStr(params))
                    .timeout(30000)
                    .execute();
            
            if (response.isOk()) {
                String body = response.body();
                log.debug("获取设备采集值响应: {}", body);
                
                try {
                    // 先解析外层响应
                    BmsApiResponse<Object> rawResponse = JSON.parseObject(body, 
                            new com.alibaba.fastjson2.TypeReference<BmsApiResponse<Object>>() {});
                    
                    if (rawResponse != null && rawResponse.getData() != null) {
                        // 创建BmsDeviceValueDto对象
                        BmsDeviceValueDto deviceValueDto = new BmsDeviceValueDto();
                        String deviceValueData = rawResponse.getData().toString();
                        JSONObject object = JSON.parseObject(deviceValueData);
                        String str = object.getString("data");
                        String time = object.getString("time");

                        deviceValueDto.setTime(DateUtils.parseDate(time));
                        deviceValueDto.setData(str);
                        
                        // 创建最终的响应对象
                        BmsApiResponse<BmsDeviceValueDto> apiResponse = new BmsApiResponse<>();
                        apiResponse.setCodeId(rawResponse.getCodeId());
                        apiResponse.setMsg(rawResponse.getMsg());
                        apiResponse.setData(deviceValueDto);
                        
                        log.debug("成功解析设备采集值数据: {}", deviceValueDto.getData());
                        return apiResponse;
                    } else {
                        log.warn("获取设备采集值响应数据为空");
                        return null;
                    }
                } catch (Exception parseException) {
                    log.error("解析设备采集值响应JSON异常: {}", body, parseException);
                    return null;
                }
            } else {
                log.error("获取设备采集值失败，状态码: {}", response.getStatus());
                return null;
            }
        } catch (Exception e) {
            log.error("获取设备采集值异常", e);
            return null;
        }
    }
} 